package cn.goktech.sports.common.utils.richText;

import com.alibaba.fastjson.JSON;
import cn.goktech.sports.common.annotation.RestAnon;
import cn.goktech.sports.common.utils.UeditorDto;
import cn.goktech.sports.common.utils.UploadUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
@RequestMapping("/rest")
public class UEditorController {
	private static final Logger logger =  LogManager.getLogger(UEditorController.class);

	@CrossOrigin(origins = "*", maxAge = 3600)//跨域，局域网内不需要配
	@RequestMapping(value="/config")
	@RestAnon
	public void config(HttpServletRequest request, HttpServletResponse response) {
		String action = request.getParameter("action");
		String type = request.getParameter("type");
		String size = request.getParameter("size");
		response.setContentType("application/json");

       if("uploadimage".equals(action) || "uploadfile".equals(action)){
		   try {
			   PrintWriter writer = response.getWriter();
			   //调用工具
			   List<String> strings = UploadUtils.uploadFile(request);
			   //返回上传成功访问的路径
			   UeditorDto ueditorDto = new UeditorDto();
			   ueditorDto.setUrl(strings.get(0));
			   ueditorDto.setSize(size);
			   ueditorDto.setType(type);
			   writer.write(JSON.toJSONString(ueditorDto));
			   return;
		   }catch (Exception e) {
			   //writer.write();
		   }
	   }
		try {
			request.setCharacterEncoding( "utf-8" );
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			logger.info(e1.toString());
		}
		String rootPath = request.getSession().getServletContext().getRealPath("/")+"config.json";//config.json文件的路径
		try {
			PrintWriter writer = response.getWriter();
			ActionEnter   a = new ActionEnter(request, rootPath);//ueditor.jar中的对象，会去读取rootpath路径下的config.json文件
			String  exec = a.exec();
			logger.info("json目录："+rootPath);
			response.setHeader("content-type","application/json;charset=utf-8");

			writer.write("("+IOUtils.toString(this.getClass().getResourceAsStream("/config.json"),"UTF-8")+")");
			writer.flush();
			writer.close();
		} catch (IOException e) {
			logger.info(e.toString());
		}
	}

	@RequestMapping(value = "/return", produces = {"application/xml;charset=UTF-8"})
	@ResponseBody
	public String test(HttpServletRequest request) {

//获取请求报文
		String ueditorDto = request.getParameter("ueditorDto");
		return ueditorDto;
	}

}
